package net.hoobo.lookzw.controller;

import com.alibaba.fastjson.JSONObject;
import net.hoobo.lookzw.service.Look;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;


@Controller
@RequestMapping("/")
public class LookController {
    @Autowired
    private Look look;


    @RequestMapping("/")
    public String hello(Model m) {
        Map data = look.getData();
        Date date = new Date();
        long delta = date.getTime()/1000-(long)(int)data.get("last_operate");
        m.addAllAttributes(data);
        m.addAttribute("delta",delta);
        if (delta<120){m.addAttribute("state","当前在线");}
        else m.addAttribute("state",formatTime(delta)+"前在线");
        long statistic = look.getStatistic(date);
        int statistic_info;
        if (statistic<1800) statistic_info=0;
        else if (statistic<3600) statistic_info=1;
        else if (statistic<3600*2) statistic_info=2;
        else if (statistic<3600*4) statistic_info=3;
        else statistic_info=4;
        m.addAttribute("info",statistic_info);
        m.addAttribute("statistic",formatTime(statistic));
        if (look.isLooking()) {m.addAttribute("isLook",true);}
        else m.addAttribute("isLook",false);
        return "hello";
    }

    @ResponseBody
    @RequestMapping(value = "/record.json", produces="application/json;charset=UTF-8")
    public String getRecords(){
        JSONObject json = new JSONObject();
        json.put("data",look.getRecords());
        return json.toJSONString();
    }

    private String formatTime(long sec){
        String res="";
        int day=(int)(sec/(24*3600));
        if (day>0){res+=day+'天';}
        int hour=(int)((sec%(24*3600))/3600);
        if (hour>0){res+=hour+"小时";}
        int minute=(int)((sec%(3600))/60);
        if (minute>=0){res+=minute+"分钟";}
        return res;
    }
}